package com.leo.tool.jdk.core;

import lombok.SneakyThrows;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CancelableTask {

    private final static Logger logger = LoggerFactory.getLogger(CancelableTask.class);

    ExecutorService executorService = Executors.newCachedThreadPool();

    @Test
    public void test() throws InterruptedException {
        logger.info(executorService.toString());
        Future<?> task = executorService.submit(this::task);
        Future<?> cancelableTask = executorService.submit(this::cancelableTask);
        Thread.sleep(10);

        logger.info(executorService.toString());
        task.cancel(true);
        cancelableTask.cancel(true);
        Thread.sleep(10);

        logger.info(executorService.toString());
    }

    @SneakyThrows
    private void cancelableTask() {
        executorService.submit(this::task).get();
    }

    private void task() {
        while (true) ;
    }
}